﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;

namespace HPortal.Backend
{
    public partial class MyFileUpload : System.Web.UI.Page
    {
        protected int UploadID = HtmlHelper.GetIdFromRequestString("UploadFileID", -1);
        protected string Directory = System.Configuration.ConfigurationManager.AppSettings["OsPortal.PortalCore.WebPathUserFilesUpload"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindcboChannel();
                BindPanelList();
                if (UploadID != -1)
                {
                    SqlDataReader dr = DatabaseHelper.SelectReader(null, "UploadFile", "UploadFileID=" + UploadID);
                    while (dr.Read())
                    {
                        txtTitle.Text = dr["Title"].ToString();
                    }
                    dr.Close();
                    cmdInsert.Text = "Lưu";
                    int PanelID = DatabaseHelper.SelectScalarInt("PanelID", "PanelList", "ItemID=" + UploadID);
                    cboChannelList.SelectedValue = DatabaseHelper.SelectScalarInt("ChannelID", "Panel", "PanelID=" + PanelID).ToString();
                    cboPanelList.SelectedValue = PanelID.ToString();
                    cboChannelList.Enabled = false;
                    cboPanelList.Enabled = false;
                    if (!checkPermission(int.Parse(cboChannelList.SelectedValue), "Edited") || !checkPermission(int.Parse(cboChannelList.SelectedValue), "Approved") || !checkPermission(int.Parse(cboChannelList.SelectedValue), "Administrated"))
                    {
                        Response.Redirect("ChannelList.aspx");
                    }
                }
                else
                    cmdInsert.Text = "Upload";
            }
        }
        private DataTable getChannel()
        {
            try
            {
                string where = string.Empty;
                if (this.Context.User.Identity.IsAuthenticated)
                {
                    string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                    foreach (string roleName in arrRoleName)
                    {
                        where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                    }

                }
                where = where.Remove(where.Length - 1);
                where = "WHERE ChannelID IN (SELECT DISTINCT ChannelID FROM [ChannelRole] WHERE ([Role] IN (" + where + ")AND (Edited=1 OR Approved=1 OR Administrated=1)))";
                string query = "SELECT * FROM [Channel] " + where + " ORDER BY [ParentID],[Priority],[ChannelID]";
                return DatabaseHelper.Select(query);
            }
            catch {
                return null;
            }
        }
        protected void BindcboChannel()
        {
            this.cboChannelList.DataSource = getChannel();
            this.cboChannelList.DataValueField = "ChannelID";
            this.cboChannelList.DataTextField = "Name";
            this.cboChannelList.DataBind();
            this.cboChannelList.SelectedIndex = 0;
        }
        protected void BindPanelList()
        {
            cboPanelList.DataSource = DatabaseHelper.Select("exec getPanelList " + cboChannelList.SelectedValue);
            cboPanelList.DataValueField = "PanelID";
            cboPanelList.DataTextField = "Header";
            cboPanelList.DataBind();
            cboPanelList.SelectedIndex = 0;
        }
        protected void cboChannelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPanelList();
        }
        public void UploadFile(System.Web.UI.HtmlControls.HtmlInputFile HtmlFullFileUpload, string FileName)
        {
            string strPath = System.IO.Path.GetFileName(FileName);
            string ServerPath = System.Web.HttpContext.Current.Server.MapPath(Directory + "\\" + strPath);
            HtmlFullFileUpload.PostedFile.SaveAs(ServerPath);
        }
        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            try
            {
                bool fileUploadisNull = true;
                string FileName = string.Empty;
                int DocumentSize = 0;
                if ((flUpload.PostedFile != null) && (flUpload.PostedFile.ContentLength != 0))
                {
                    FileName = flUpload.PostedFile.FileName;
                    string FileType = flUpload.PostedFile.ContentType;
                    byte[] FileContent = new byte[flUpload.PostedFile.ContentLength];
                    this.flUpload.PostedFile.InputStream.Read(FileContent, 0, FileContent.Length);
                    DocumentSize = FileContent.Length / 1000;
                    fileUploadisNull = false;
                }

                string Title = txtTitle.Text.Replace("'", "''");
                if (UploadID == -1)//INSERT
                {
                    if (!fileUploadisNull)
                    {
                        string FileType = flUpload.PostedFile.ContentType;
                        string FileExt = FileName.Substring(FileName.LastIndexOf(".")+1);
                        UploadID = DatabaseHelper.InsertIdentity(new string[] { "N@FileType","@FileExt", "N@Title","N@AuthorName", "@DocumentSize" },
                            new string[] { FileType, FileExt, Title, Context.User.Identity.Name, DocumentSize.ToString() }, "UploadFile");
                        this.UploadFile(flUpload, UploadID.ToString() + "." + FileExt);
                        DatabaseHelper.Insert("INSERT INTO [PanelList] ([ItemID],[PanelID]) VALUES (" + UploadID + "," + cboPanelList.SelectedValue + ")");
                    }
                }
                else//UPDATE
                {
                    if (!fileUploadisNull)
                    {
                        string FileType = flUpload.PostedFile.ContentType;
                        string FileExt = FileName.Substring(FileName.LastIndexOf(".")+1);
                        this.UploadFile(flUpload, UploadID.ToString() + "." + FileExt);
                        DatabaseHelper.Update(
                            new string[] { "N@FileType", "@FileExt", "N@Title", "N@AuthorName", "@DocumentSize" },
                            new string[] { FileType, FileExt, Title, Context.User.Identity.Name, DocumentSize.ToString() }, "UploadFile", "UploadFileID=" + UploadID);
                    }
                    else
                    {
                        DatabaseHelper.Update(
                            new string[] { "N@Title", "N@AuthorName"},
                            new string[] { Title, Context.User.Identity.Name }, "UploadFile", "UploadFileID=" + UploadID);
                    }
                }
                Response.Redirect("UploadFileList.aspx?ChannelID=" + cboChannelList.SelectedValue + "&PanelID=" + cboPanelList.SelectedValue);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private Boolean checkPermission(int ChannelID, string Permission)
        {
            string where = string.Empty;
            if (this.Context.User.Identity.IsAuthenticated)
            {
                string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                foreach (string roleName in arrRoleName)
                {
                    where += DatabaseHelper.EscapeQuoteUnicode(roleName) + ",";
                }

            }
            where = where.Remove(where.Length - 1);
            string query = "SELECT count(*) FROM [ChannelRole] WHERE ([Role] IN (" + where + ") AND ChannelID=" + ChannelID + " AND " + Permission + "=1)";
            if (int.Parse(DatabaseHelper.SelectScalar(query).ToString()) > 0)
                return true;
            else
                return false;
        }
    }
}